# coding=utf8
from xml.dom.minidom import parse


def print_child_onclick_node(node, listener_name="this"):
    android_init_text = []
    for child in node.childNodes:
        keys = []
        attributes = child.attributes
        if attributes is not None:
            keys = attributes.keys()
        # find android id key
        if "android:id" in keys:
            android_id = str(child.attributes["android:id"].value).replace("@+id/", "")
            init_text = "{0}.setOnClickListener({1});".format(android_id, listener_name)
            android_init_text.append(init_text)

        print_child_onclick_node(child, listener_name=listener_name)

    for i in android_init_text:
        print(i)


def gen_onclick(path, listener_name="this"):
    xmldoc = parse(path)
    root = xmldoc.documentElement
    print_child_onclick_node(root, listener_name)


def print_child_find_view_node(node, view_name):
    android_init_text = []
    for child in node.childNodes:
        keys = []
        attributes = child.attributes
        if attributes is not None:
            keys = attributes.keys()
        # find android id key
        if "android:id" in keys:
            android_id = str(child.attributes["android:id"].value).replace("@+id/", "")
            init_text = "{0} = ({1}){2}findViewById(R.id.{0});".format(android_id, str(child.nodeName), view_name)
            android_init_text.append(init_text)

        print_child_find_view_node(child, view_name)

    for i in android_init_text:
        print(i)


def print_child_define_node(node):
    android_init_text = []
    for child in node.childNodes:
        keys = []
        attributes = child.attributes
        if attributes is not None:
            keys = attributes.keys()
        # find android id key
        if "android:id" in keys:
            android_id = str(child.attributes["android:id"].value).replace("@+id/", "")
            init_text = "{1} {0};".format(android_id, str(child.nodeName))
            android_init_text.append(init_text)

        print_child_define_node(child)

    for i in android_init_text:
        print(i)


def gen_find_view(path, view_name=""):
    xmldoc = parse(path)
    root = xmldoc.documentElement
    print_child_find_view_node(root, view_name)


def gen_define(path):
    xmldoc = parse(path)
    root = xmldoc.documentElement
    print_child_define_node(root)

if __name__ == '__main__':
    gen_define(r"/Users/zhangmike/Documents/workspace/umpApp/res/layout/activity_customer_detail.xml")
    print("\n")
    gen_find_view(r"/Users/zhangmike/Documents/workspace/umpApp/res/layout/activity_customer_detail.xml", view_name="view.")
    print("\n")
    gen_onclick(r"/Users/zhangmike/Documents/workspace/umpApp/res/layout/activity_customer_detail.xml")
    print("\n")
